// src/services/index.ts
import { message } from 'ant-design-vue';
import axios from 'axios';
import { useTenantStore } from '@/stores/global';

const getBearerAuthHeader = () => {
  const storedToken = localStorage.getItem('access_token');
  return 'bearer ' + storedToken;
};


export let httpService: axios.AxiosInstance;

export function initHttpService() {
  httpService = axios.create({
    baseURL: '',
    timeout: 30000,
    headers: {
      'Content-Type': 'application/json',
    },
  });

  httpService.interceptors.request.use(
    config => {
      //config.headers['X-Tenant-Id'] = getTenantId();
      config.headers.Authorization = getBearerAuthHeader();
      return config;
    },
    error => {
      return Promise.reject(error);
    },
  );

  httpService.interceptors.response.use(
    async ({ status, data }) => {
      if (status !== 200) {
        return Promise.reject({ status });
      }
      const { code, msg, ...rest } = data;

      if (code == '611') {
        message.error(msg);
        return;
      }
      if (code == '555') {
        message.error('未知异常');
        return;
      }
      if (code == '1101') {
        message.error(`原密码错误`);
        return;
      }

      return { code, msg, ...rest };
    },
    async error => {
      // https状态码 处理
      if (error && error.response && error.response.status) {
        switch (error.response.status) {
          case 400:
            error.message = '错误请求';
            break;
          case 401:
            error.message = '未授权，请重新登录';
            break;
          case 403:
            error.message = '拒绝访问';
            break;
          case 404:
            error.message = '请求错误,未找到该资源';
            break;
          case 405:
            error.message = '请求方法未允许';
            break;
          case 408:
            error.message = '请求超时';
            break;
          case 409:
            error.message = '登录失效,请重新登录';
            break;
          case 500:
            error.message = '服务器端出错';
            break;
          case 501:
            error.message = '网络未实现';
            break;
          case 502:
            error.message = '网络错误';
            break;
          case 503:
            error.message = '服务不可用';
            break;
          case 504:
            error.message = '网络超时';
            break;
          case 505:
            error.message = 'http版本不支持该请求';
            break;
          default:
            error.message = `未知错误${error.response.status}`;
        }
      } else {
        error.message = '服务器未响应';
      }
      if (error.response?.status !== 409) {
        message.warn(error.message);
      }
      if (error.response?.status === 409 || error.response?.status === 403) {
        window.dispatchEvent(new CustomEvent('logout'));
      }

      return false;
    },
  );
}

export function baseRequest(url, params = {}) {
  return new Promise((resolve, reject) => {
    httpService({ url: `${url}.admin`, method: 'post', data: params })
      .then(response => {
        if (response != undefined) {
          resolve(response);
        }
      })
      .catch(error => {
        reject(error);
      });
  });
}

export async function login(params: Login.LoginParams) {
  return new Promise((resolve, reject) => {
    const url = '/api/auth/oauth/token';
    httpService({ url, method: 'post', params })
      .then(response => {
        if (response != undefined) {
          resolve(response);
        }
      })
      .catch(error => {
        reject(error);
      });
  });
}

export async function page<T>(url: string, params: API.PageParams) {
  const { current, pageSize, ...data } = params;
  return await baseRequest(`${url}/page`, {
    pageNum: current,
    pageSize: pageSize,
    ...data,
  });
}

export async function list<T>(url: string, data?: any) {
  return await baseRequest<T>(`${url}/list`, data || {});
}

export async function update<T>(url: string, data: any) {
  return await baseRequest<T>(`${url}/update`, data);
}

export async function add<T>(url: string, data: any) {
  return await baseRequest<T>(`${url}/add`, data);
}

export async function remove<T>(url: string, id: string) {
  return await baseRequest<T>(`${url}/delete`, id);
}

export async function count<T>(url: string, data?: any) {
  return await baseRequest<T>(`${url}/count`, data);
}

export async function get<T>(url: string, id: string) {
  return await baseRequest<T>(`${url}/one`, id);
}

export async function getByData<T>(url: string, data: any) {
  return await baseRequest<T>(`${url}/one`, data);
}

export async function getData<T>(url: string, data?: any) {
  return await baseRequest<T>(`${url}`, data);
}

export const handleAdd = async (url: string, fields: any) => {
  const hide = message.loading('正在添加');

  try {
    const { data }: API.BooleanResult = await add(url, { ...fields });
    hide();
    if (data) {
      message.success('添加成功');
    } else {
      message.error('添加失败');
    }
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

export const handleUpdate = async (url: string, fields: any, currentRow?: any) => {
  const hide = message.loading('正在更新');
  try {
    const { data }: API.BooleanResult = await update(url, {
      ...currentRow,
      ...fields,
    });
    hide();
    if (data) {
      message.success('更新成功');
    } else {
      message.error('更新失败');
    }
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

export const handleRemove = async (url: string, id: string) => {
  const hide = message.loading('正在删除');

  try {
    const { data }: API.BooleanResult = await remove(url, id);
    hide();
    if (data) {
      message.success('删除成功，即将刷新');
    } else {
      message.error('删除失败');
    }
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

export const handleRemoveList = async (url: string, selectedRows: API.TableId[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    selectedRows.map(async row => await remove(url, row.id));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};
